package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.UserEducationVo;
import com.ruoyi.system.mapper.ActivityManagementMapper;
import com.ruoyi.system.mapper.ActivityUserSignatureMapper;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.IActivityManagementService;
import com.ruoyi.system.service.IActivitySummaryService;
import com.ruoyi.system.service.IDeptFileArchivedService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.Activity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-02
 */
@Service
@Slf4j
public class ActivityManagementServiceImpl implements IActivityManagementService
{
    @Autowired
    private ActivityManagementMapper ActivityManagementMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ActivityUserSignatureMapper activityUserSignatureMapper;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private IActivitySummaryService activitySummaryService;
    @Autowired
    private IDeptFileArchivedService deptFileArchivedService;

    /**
     * 查询活动管理
     *
     * @param id 活动管理主键
     * @return 活动管理
     */
    @Override
    public ActivityManagement selectActivityManagementById(Long id)
    {
        ActivityManagement ActivityManagement = ActivityManagementMapper.selectActivityManagementById(id);
        //处理参会人员
        String activityAttendeeType = ActivityManagement.getActivityAttendeeType();
        if("1".equals(activityAttendeeType)){
            String activityAttendee = ActivityManagement.getActivityAttendee();
            if(StringUtils.isNotBlank(activityAttendee)){
                List<String> userIdList = Arrays.asList(activityAttendee.split(","));
                ArrayList<SysUser> userList = new ArrayList();
                for(String userId : userIdList){
                    SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                    userList.add(user);
                }
                ActivityManagement.setUserIdList(userIdList);
                ActivityManagement.setUserList(userList);
            }
        }
        //处理活动材料
        String activityMaterial = ActivityManagement.getActivityMaterial();
        if(StringUtils.isNotBlank(activityMaterial)){
            List<String> activityMateriaList = Arrays.asList(activityMaterial.split(","));
            ActivityManagement.setActivityMaterialList(activityMateriaList);
        }

        return ActivityManagement;
    }

    /**
     * 查询活动管理列表
     *
     * @param ActivityManagement 活动管理
     * @return 活动管理
     */
    @Override
    public List<ActivityManagement> selectActivityManagementList(ActivityManagement ActivityManagement)
    {
        List<ActivityManagement> ActivityManagementList = ActivityManagementMapper.selectActivityManagementList(ActivityManagement);
        for(ActivityManagement activity : ActivityManagementList){
            //处理参会人员
            String activityAttendeeType = activity.getActivityAttendeeType();
            if("1".equals(activityAttendeeType)){
                String activityAttendee = activity.getActivityAttendee();
                if(StringUtils.isNotBlank(activityAttendee)){
                    List<String> userIdList = Arrays.asList(activityAttendee.split(","));
                    ArrayList<SysUser> userList = new ArrayList();
                    for(String userId : userIdList){
                        SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                        userList.add(user);
                    }
                    activity.setUserIdList(userIdList);
                    activity.setUserList(userList);
                }
            }

            //处理活动材料
            String activityMaterial = ActivityManagement.getActivityMaterial();
            if(StringUtils.isNotBlank(activityMaterial)){
                List<String> activityMateriaList = Arrays.asList(activityMaterial.split(","));
                ActivityManagement.setActivityMaterialList(activityMateriaList);
            }
            String createBy = activity.getCreateBy();
            SysUser user = sysUserService.selectUserById(Long.valueOf(createBy));
            activity.setCreateBy(user.getNickName());
        }
        return ActivityManagementList;
    }

    /**
     * 新增活动管理
     *
     * @param activityManagement 活动管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertActivityManagement(ActivityManagement activityManagement)
    {
        activityManagement.setCreateTime(DateUtils.getNowDate());
        //参会人员
        List<String> userIdList = activityManagement.getUserIdList();
        String activityAttendee = StringUtils.join(userIdList, ",");
        activityManagement.setActivityAttendee(activityAttendee);
        //活动材料
        List<String> activityMaterialList = activityManagement.getActivityMaterialList();
        String activityMaterial = StringUtils.join(activityMaterialList, ",");
        activityManagement.setActivityMaterial(activityMaterial);

        ActivityManagementMapper.insertActivityManagement(activityManagement);

        //如果参会人员是本部门人员或者全体人员
        if(CollectionUtils.isEmpty(userIdList)){
            String activityAttendeeType = activityManagement.getActivityAttendeeType();
            if("0".equals(activityAttendeeType)){
                //本部门人员
                SysUser user = new SysUser();
                user.setDeptId(activityManagement.getDeptId());
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                userIdList = sysUsers.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
            }else if("2".equals(activityAttendeeType)){
                //全体人员
                SysUser user = new SysUser();
                List<SysUser> sysUsers = sysUserService.selectUserList(user);
                userIdList = sysUsers.stream().map(o -> o.getUserId().toString()).collect(Collectors.toList());
            }
        }
        //补录活动手动添加签到信息
        String clearingActivity = activityManagement.getClearingActivity();
        String activitySignature = activityManagement.getActivitySignature();
        //是否补录活动（0:不是1：是）并且 活动签到（0:不签到 1:定位签到）
        if("0".equals(clearingActivity)&&"1".equals(activitySignature)){
            //添加活动签到人员信息
            for(String userId : userIdList){
                ActivityUserSignature activityUserSignature = new ActivityUserSignature();
                SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                activityUserSignature.setActivityId(activityManagement.getId());
                activityUserSignature.setUserId(Long.valueOf(userId));
                activityUserSignature.setUserName(user.getNickName());
                activityUserSignature.setPhonenumber(user.getPhonenumber());
                activityUserSignature.setUserDeptName(user.getDept().getDeptName());
                activityUserSignature.setUserPartyType(user.getPartyType());
                List<Long> postIds = sysPostMapper.selectPostListByUserId(Long.valueOf(userId));
                String postId = StringUtils.join(postIds, ",");
                activityUserSignature.setUserPostId(postId);
                activityUserSignature.setCreateTime(DateUtils.getNowDate());
                activityUserSignature.setCreateBy(activityManagement.getCreateBy());
                activityUserSignatureMapper.insertActivityUserSignature(activityUserSignature);
            }

        }
        //创建会议归纳文件夹
        DeptFileArchived deptFileArchived = new DeptFileArchived();
        deptFileArchived.setParentId(2L);
        deptFileArchived.setDeptId(activityManagement.getDeptId());
        deptFileArchived.setFileName(activityManagement.getActivityTheme());
        deptFileArchived.setFileType("0");
        deptFileArchived.setCreateBy(activityManagement.getCreateBy());
        deptFileArchived.setAssociationId(String.valueOf(activityManagement.getId()));
        SysUser user = sysUserService.selectUserById(Long.valueOf(activityManagement.getCreateBy()));
        deptFileArchived.setCreateName(user.getNickName());
        deptFileArchivedService.insertDeptFileArchived(deptFileArchived);
        return AjaxResult.success("添加成功");
    }

    /**
     * 修改活动管理
     *
     * @param activityManagement 活动管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateActivityManagement(ActivityManagement activityManagement)
    {
        activityManagement.setUpdateTime(DateUtils.getNowDate());
        //活动结束直接发起活动纪要
        String status = activityManagement.getStatus();
        if("2".equals(status)){
            ActivityManagement ActivityManagementVo = ActivityManagementMapper.selectActivityManagementById(activityManagement.getId());
            ActivitySummary activitySummary = new ActivitySummary();
            activitySummary.setActivityId(activityManagement.getId());
            String activityEndTime = ActivityManagementVo.getActivityEndTime();
            DateTime activityEndTimeDate = DateUtil.parse(activityEndTime, "yyyy-MM-dd HH:mm:ss");
            //截至时间是会决结束日期3天之后
            Date dateTime = DateUtil.offsetDay(activityEndTimeDate, 3);
            activitySummary.setEndTime(dateTime);
            activitySummaryService.insertActivitySummary(activitySummary);
        }
        return ActivityManagementMapper.updateActivityManagement(activityManagement);
    }


    /**
     * 删除活动管理信息
     *
     * @param id 活动管理主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteActivityManagementById(Long id)
    {
        int i = ActivityManagementMapper.deleteActivityManagementById(id);
        activityUserSignatureMapper.deleteActivityUserSignatureByActivityId(id);
        return i;
    }

    /**
     * 查询活动活动签到统计列表
     *
     * @param activityManagement 活动管理
     * @return 活动管理集合
     */
    @Override
    public List<ActivityManagement> selectActivitySignaturelist(ActivityManagement activityManagement){
        List<ActivityManagement> ActivityManagementList = ActivityManagementMapper.selectActivityManagementList(activityManagement);
        for(ActivityManagement activity : ActivityManagementList){
            Long id = activity.getId();
            ActivityUserSignature activityUserSignature = new ActivityUserSignature();
            activityUserSignature.setActivityId(id);
            List<ActivityUserSignature> activityUserSignatureList = activityUserSignatureMapper.selectActivityUserSignatureList(activityUserSignature);
            //正常签到、迟到、补签
            long count = activityUserSignatureList.stream().filter(o -> o.getStatus().equals("1") || o.getStatus().equals("4")|| o.getStatus().equals("3")).count();
            activity.setSignatureCount((int) count);
            activity.setActivityAttendeeCount(activityUserSignatureList.size());
        }
        return ActivityManagementList;
    }

    /**
     * 查询参加的活动列表
     *
     * @param activityManagement 活动管理
     * @return 活动管理集合
     */
    @Override
    public List<ActivityManagement> selectJoinActivityManagementList(ActivityManagement activityManagement){
        List<ActivityManagement> resultList = new ArrayList();
        List<ActivityManagement> ActivityManagementList = ActivityManagementMapper.selectActivityManagementList(activityManagement);
        for(ActivityManagement activity : ActivityManagementList){
            //处理参会人员
            String activityAttendeeType = activity.getActivityAttendeeType();
            if("1".equals(activityAttendeeType)){
                String activityAttendee = activity.getActivityAttendee();
                if(StringUtils.isNotBlank(activityAttendee)){
                    List<String> userIdList = Arrays.asList(activityAttendee.split(","));
                    ArrayList<SysUser> userList = new ArrayList();
                    for(String userId : userIdList){
                        SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                        userList.add(user);
                    }
                    activity.setUserIdList(userIdList);
                    activity.setUserList(userList);
                    if(userIdList.contains(activityManagement.getUserId())){
                        resultList.add(activity);
                    }
                }
            }else if("0".equals(activityAttendeeType)){
                //当前登陆人
                SysUser user1 = sysUserService.selectUserById(Long.valueOf(activityManagement.getUserId()));
                String createBy = activity.getCreateBy();
                SysUser user2 = sysUserService.selectUserById(Long.valueOf(createBy));
                if(user1.getDeptId().equals(user2.getDeptId())){
                    resultList.add(activity);
                }

            }else if("2".equals(activityAttendeeType)){
                resultList.add(activity);
            }
        }
        return resultList;
    }


    /**
     * 查询已参加的活动列表
     *
     * @param activityManagement 活动管理
     * @return 活动管理集合
     */
    @Override
    public List<ActivityManagement> selectjoinedlist(ActivityManagement activityManagement){
        List<ActivityManagement> resultList = new ArrayList();
        List<ActivityManagement> ActivityManagementList = ActivityManagementMapper.selectJoinedActivityManagementList(activityManagement);
        for(ActivityManagement activity : ActivityManagementList){
            ActivityUserSignature activityUserSignature = new ActivityUserSignature();
            activityUserSignature.setUserId(Long.valueOf(activityManagement.getUserId()));
            activityUserSignature.setActivityId(Long.valueOf(activity.getId()));
            ActivityUserSignature userSignature = activityUserSignatureMapper.selectActivityUserSignature(activityUserSignature);
            //排除没有签到和请假的活动
            if(!ObjectUtils.isEmpty(userSignature)){
                String status = userSignature.getStatus();
                if(status.equals("0")||status.equals("2")){
                    continue;
                }
            }
            //处理参会人员
            String activityAttendeeType = activity.getActivityAttendeeType();
            if("1".equals(activityAttendeeType)){
                String activityAttendee = activity.getActivityAttendee();
                if(StringUtils.isNotBlank(activityAttendee)){
                    List<String> userIdList = Arrays.asList(activityAttendee.split(","));
                    ArrayList<SysUser> userList = new ArrayList();
                    for(String userId : userIdList){
                        SysUser user = sysUserService.selectUserById(Long.valueOf(userId));
                        userList.add(user);
                    }
                    activity.setUserIdList(userIdList);
                    activity.setUserList(userList);
                    if(userIdList.contains(activityManagement.getUserId())){
                        resultList.add(activity);
                    }
                }
            }else if("0".equals(activityAttendeeType)){
                //当前登陆人
                SysUser user1 = sysUserService.selectUserById(Long.valueOf(activityManagement.getUserId()));
                String createBy = activity.getCreateBy();
                SysUser user2 = sysUserService.selectUserById(Long.valueOf(createBy));
                if(user1.getDeptId().equals(user2.getDeptId())){
                    resultList.add(activity);
                }

            }else if("2".equals(activityAttendeeType)){
                resultList.add(activity);
            }
        }
        return resultList;
    }

    /**
     * 导出会议通知
     */
    @Override
    public AjaxResult exportActivityNotify(ActivityManagement activityManagement, HttpServletResponse response){
        ActivityManagement activity = ActivityManagementMapper.selectActivityManagementById(activityManagement.getId());
        String activityTheme = activity.getActivityTheme();
        String associateItem = activity.getAssociateItem();
        String activityStartTime = activity.getActivityStartTime();
        String year = activityStartTime.substring(0, 5);
        String month = activityStartTime.substring(5, 7);
        String day = activityStartTime.substring(8, 10);
        String activityEndTime = activity.getActivityEndTime();
        String activityPlace = activity.getActivityPlace();
        String compereName = activity.getCompereName();
        String activityContent = activity.getActivityContent();
        String activityRequire = activity.getActivityRequire();
        String deptName = activity.getDeptName();
        Date startTime = DateUtil.parse(activityStartTime, "yyyy-MM-dd");
        Date dateTime = DateUtil.offsetDay(startTime, -7);
        String notifyTime = DateUtil.format(dateTime, "yyyy年MM月dd日");

        try {
            //组装数据
            Map<String, Object> map = new HashMap<>();
            map.put("activityTheme",activityTheme);
            map.put("associateItem",associateItem);
            map.put("month",month);
            map.put("day",day);
            map.put("activityStartTime",activityStartTime);
            map.put("activityEndTime",activityEndTime);
            map.put("activityPlace",activityPlace);
            map.put("compereName",compereName);
            map.put("activityContent",activityContent);
            map.put("activityRequire",activityRequire);
            map.put("deptName",deptName);
            map.put("notifyTime",notifyTime);

            //获取文件名称
            String name = activity.getActivityTheme();
            //获取模板
            ClassPathResource classPathResource = new ClassPathResource("static/actNotify.docx");
            String resource = classPathResource.getURL().getPath();
            ConfigureBuilder builder = Configure.builder();
            builder.useSpringEL();
            XWPFTemplate template = XWPFTemplate.compile(resource,builder.build()).render(map);


//            //设置导出路径  创建一个word目录
//            String path = "D:/word/";
//            File file = new File(path);
//            //如果不存在则创建
//            if (!file.exists()) {
//                file.mkdirs();
//            }
//            //输出到指定目录下
//            String filePath = "D:/word/"+name+".docx";
//            FileOutputStream ostream = new FileOutputStream(filePath);
//            template.write(ostream);
//            //关闭输出流
//            ostream.flush();
//            ostream.close();
//            template.close();

            response.setHeader("Content-Disposition", "attachment; filename="+""+"activitynotify.docx");
            response.setHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            OutputStream outputStream = response.getOutputStream();
            template.write(outputStream);
            outputStream.close();
            template.close();

        }catch(IOException e){
            //异常处理
            log.error("文件导出错误", e);
            return AjaxResult.success("导出失败");
        }
        return AjaxResult.success("导出成功");
    }


    /**
     * 导出会议签到
     */
    @Override
    public AjaxResult exportActivitySignature(ActivityManagement activityManagement, HttpServletResponse response){
        ActivityManagement activity = ActivityManagementMapper.selectActivityManagementById(activityManagement.getId());
        ActivityUserSignature activityUserSignature = new ActivityUserSignature();
        activityUserSignature.setActivityId(activityManagement.getId());
        List<ActivityUserSignature> ActivityUserSignatureList = activityUserSignatureMapper.selectActivityUserSignatureList(activityUserSignature);
        try {
            //获取数据
            String activityTheme = activity.getActivityTheme();
            String activityStartTime = activity.getActivityStartTime();
            String activityPlace = activity.getActivityPlace();
            String compereName = activity.getCompereName();
            // TODO 渲染其他类型的数据请参考官方文档
            //组装表格列表数据
            int i =0;
            List<Map<String,Object>> detailList=new ArrayList<Map<String,Object>>();
            for(ActivityUserSignature signature : ActivityUserSignatureList){
                Map<String, Object> detailMap = new HashMap<String, Object>();
                String userPostId = signature.getUserPostId();
                if(StringUtils.isNotBlank(userPostId)){
                    List<String> userPostIdList = Arrays.asList(userPostId.split(","));
                    List<String> postNameList = new ArrayList();
                    for(String postId : userPostIdList){
                        SysPost sysPost = sysPostMapper.selectPostById(Long.valueOf(postId));
                        postNameList.add(sysPost.getPostName());
                    }
                    String postNames = String.join(",", postNameList);
                    signature.setPostNames(postNames);
                }
                //序号
                detailMap.put("index", i+1);
                //姓名
                detailMap.put("user_name", signature.getUserName());
                //职务
                detailMap.put("post_name",signature.getPostNames());
                detailList.add(detailMap);
                i++;
            }
            //word模板地址获取方式一：缺点---打jar包获取不到该路径
//              String basePath=ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/template/";
//              String resource =basePath+"order1.docx";//word模板地址
            //word模板地址获取方式二：优点---相比上一种方式，这种方法不会在linux或者jar上失效
            ClassPathResource classPathResource = new ClassPathResource("static/actSignature.docx");
            String resource = classPathResource.getURL().getPath();
            //渲染表格
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder().bind("detailList", policy).build();

            XWPFTemplate template = XWPFTemplate.compile(resource, config).render(
                    new HashMap<String, Object>() {{
                        put("detailList", detailList);
                        put("activityTheme", activityTheme);
                        put("activityStartTime", activityStartTime);
                        put("activityPlace",activityPlace);
                        put("compereName",compereName);
                    }}
            );

//            //设置导出路径  创建一个word目录
//            String path = "D:/word/";
//            File file = new File(path);
//            //如果不存在则创建
//            if (!file.exists()) {
//                file.mkdirs();
//            }
//            //=================生成文件保存在本地D盘某目录下=================
//            //输出到指定目录下
//            String filePath = "";
//            filePath = path+ActivityTheme+"签到表"+".docx";
//            FileOutputStream ostream = new FileOutputStream(filePath);
//            template.write(ostream);
//            //关闭输出流
//            ostream.flush();
//            ostream.close();
//            template.close();

            response.setHeader("Content-Disposition", "attachment; filename="+""+"activitysignature.docx");
            response.setHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8");
            response.setCharacterEncoding("utf-8");
            OutputStream outputStream = response.getOutputStream();
            template.write(outputStream);
            outputStream.close();
            template.close();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导出失败");
        }
        return AjaxResult.success("导出成功");
    }


    /**
     * 党建大数据 活动分布
     */
    @Override
    public List<UserEducationVo>  activityStructure(String queryYear){
        List<UserEducationVo> userEducationVolist= Lists.newArrayList();
        String startTime = queryYear+"-01-01 00:00:00";
        String endTime = queryYear+"-12-31 23:59:59";
        ActivityManagement activityManagement = new ActivityManagement();
        activityManagement.setActivityStartTime(startTime);
        activityManagement.setActivityEndTime(endTime);
        List<ActivityManagement> activityManagements = ActivityManagementMapper.selectActivityManagementList(activityManagement);
        Map<String, List<ActivityManagement>> collect = activityManagements.stream().collect(Collectors.groupingBy(ActivityManagement::getActivityType));
        for(Map.Entry<String, List<ActivityManagement>> entry : collect.entrySet()){
            String key = entry.getKey();
            List<ActivityManagement> value = entry.getValue();
            UserEducationVo userEducationVo = new UserEducationVo();
            userEducationVo.setName(key);
            userEducationVo.setValue(value.size());
            userEducationVolist.add(userEducationVo);
        }
        return userEducationVolist;
    }
}
